import io, { Socket } from 'socket.io-client'
import { messageHandler } from '@/api/socket'
import { SocketMessage } from '@/constants/'
import { useAccountStore } from '@/store'

// 定义 log 对象及其各种日志方法
const log = {
	success: (...args: any[]) => console.log(`%c${args.join(' ')}`, 'color: #00be7a;'),
	warn: (...args: any[]) => console.log(`%c${args.join(' ')}`, 'color: #febc04;'),
	error: (...args: any[]) => console.log(`%c${args.join(' ')}`, 'color: #f80563;'),
	info: (...args: any[]) => console.debug(`%c${args.join(' ')}`, 'color: #0688f9;')
}

export let socket: Socket | undefined

export const initSocket = () => {
	if (socket) {
		socket?.disconnect()
	}
	const accountStore = useAccountStore()
	const url: string = import.meta.env.DEV ? import.meta.env.VITE_SOCKET_URL : '/'
	socket = io(url, {
		// path: '/socket.io',
		// addTrailingSlash: false,
		transports: ['websocket', 'polling'],
		query: { authorization: `Bearer ${accountStore.token}` }
	})
	socket.on('connect', () => {
		log.success('socket connected; 可勾选日志级别中的 Verbose (详细) 查看 socket message 的输出')
		// setTimeout(() => {
		// 	if (initialed) {
		// 		socketReconnected()
		// 	}
		// 	bus.$emit(!initialed ? EVENT_SOCKET_CONNECT : EVENT_SOCKET_RECONNECT)
		// 	initialed = true
		// }, 1000)
	})
	socket.on('disconnect', () => {
		log.warn('socket disconnect')
	})
	socket.on('message', (data: SocketMessage) => {
		log.info('socket message', data?.command)
		if (data && typeof data === 'object') {
			messageHandler(data)
		}
	})
	socket.on('connect_error', (error) => {
		log.error(error)
	})
}

// export const disconnectSocket = () => {
//   socket.disconnect()
// }

export const sendSocket = (type: string, data: any) => {
	socket?.emit('message', { type, data })
}
